<template>
  <div class="container">
    <div class="app-container">
      <div class="left">
        <el-input v-model="queryParams.keyword" v-focus style="margin-bottom:10px" type="text" prefix-icon="el-icon-search" size="small" placeholder="输入员工姓名全员搜索" @input="searchEmployee" />
        <!-- 树形组件 -->
        <el-tree
          ref="deptTree"
          node-key="id"
          :data="depts"
          :props="{label:'name'}"
          default-expand-all
          :expand-on-click-node="false"
          highlight-current
          @current-change="selectNode"
        />
      </div>
      <div class="right">
        <el-row class="opeate-tools" type="flex" justify="end">
          <el-button size="mini" type="primary" @click="$router.push('/employee/detail')">添加员工</el-button>
          <el-button size="mini" @click="showExcelDialog=true">excel导入</el-button>
          <el-button size="mini" @click="exportExcel">excel导出</el-button>
        </el-row>
        <!-- 表格组件 -->
        <el-table
          :data="list"
          style="width: 100%"
        >
          <el-table-column
            label="头像"
            width="width"
            align="center"
            prop="staffPhoto"
          >
            <template v-slot="{row}">
              <el-avatar v-if="row.staffPhoto" :src="row.staffPhoto" :size="30" />
              <span v-else class="username">{{ row.username?.charAt(0) }}</span>
            </template>
          </el-table-column>
          <el-table-column
            prop="username"
            label="姓名"
            width="width"
            align="center"
          />
          <el-table-column
            prop="mobile"
            label="手机号"
            width="width"
            align="center"
          />
          <el-table-column
            prop="workNumber"
            label="工号"
            width="width"
            align="center"
          />
          <el-table-column
            prop="formOfEmployment"
            label="聘用形式"
            width="width"
            align="center"
          >
            <template v-slot="{row}">
              <span>{{ row.formOfEmPloyment===1?'正式':'非正式' }}</span>
            </template>
          </el-table-column>

          <el-table-column
            prop="departmentName"
            label="部门"
            width="width"
            align="center"
          />
          <el-table-column
            prop="timeOfEntry"
            label="入职时间"
            width="width"
            align="center"
          />
          <el-table-column
            label="操作"
            width="width"
            align="center"
          >
            <template v-slot="{row}">
              <el-button type="text" size="mini" @click="$router.push(`employee/detail/${row.id}`)">查看</el-button>
              <el-button type="text" size="mini" @click="btnRole(row.id)">角色</el-button>
              <el-popconfirm
                title="确定删除该员工吗？"
                style="margin-left:10px"
                @onConfirm="delEmployee(row.id)"
              >
                <el-button slot="reference" type="text" size="mini">删除</el-button>
              </el-popconfirm>

            </template></el-table-column>
        </el-table>
        <!-- 分页 -->
        <el-row type="flex" justify="end" align="middle">
          <el-pagination
            :current-page="queryParams.page"
            :page-size="queryParams.pagesize"
            layout="total,prev,pager,next"
            :total="total"
            @current-change="changePage"
          />
        </el-row>
      </div>
    </div>
    <import-excel :show-excel-dialog.sync="showExcelDialog" @uploadSuccess="getEmployeeList()" />
    <el-dialog
      title="分配角色"
      :visible.sync="showRoleDialog"
    >
      <el-checkbox-group v-model="roleIds">
        <el-checkbox v-for="item in roleList" :key="item.id" :label="item.id">{{ item.name }}</el-checkbox>
      </el-checkbox-group>

      <el-row type="flex" justify="center" style="margin-top:20px">
        <el-button @click="showRoleDialog = false">取 消</el-button>
        <el-button type="primary" @click="btnRoleOk">确 定</el-button>
      </el-row>
    </el-dialog>

  </div>
</template>

<script>
import { getDepartment } from '@/api/department'
import { transListToTreeData } from '@/utils'
import { getEmployeeList, exportExcel, delEmployee, getEnableRoleList, getEmployeeDetail, assignRoles } from '@/api/employee'
import FileSaver from 'file-saver'
import ImportExcel from './components/import-excel.vue'
export default {
  name: 'Employee',
  components: { ImportExcel },
  data() {
    return {
      showRoleDialog: false,
      showExcelDialog: false,
      depts: [],
      list: [],
      queryParams: {
        departmentId: null,
        page: 1,
        pagesize: 10,
        keyword: ''
      },
      total: 0,
      roleList: [], // 可用角色列表
      roleIds: [] // 用于绑定的
    }
  },
  created() {
    this.getDepartment()
    this.getEmployeeList()
  },
  methods: {
    async getDepartment() {
      this.depts = transListToTreeData(await getDepartment(), 0)
      // 查询参数的id为点击的当前节点的id
      this.queryParams.departmentId = this.depts[0].id
      this.$nextTick(() => {
        // 异步的。不然数据还没渲染完就获取了  undefined
        this.$refs.deptTree.setCurrentKey(this.queryParams.departmentId)
      })
    },
    selectNode(node) {
      this.queryParams.departmentId = node.id // 重新记录了参数
      this.queryParams.page = 1 // 设置第一页
      this.getEmployeeList()
    },
    async getEmployeeList() {
      const { rows, total } = await getEmployeeList(this.queryParams)
      this.list = rows
      this.total = total
    },
    changePage(newPage) {
      this.queryParams.page = newPage
      this.getEmployeeList()
    },
    searchEmployee() {
      this.queryParams.size = 1
      clearTimeout(this.timer)
      this.timer = setTimeout(() => {
        this.getEmployeeList()
      }, 500)
    },
    async exportExcel() {
      FileSaver.saveAs(await exportExcel(), '员工excel表.xlsx')
    },
    // 删除员工
    async delEmployee(id) {
      await delEmployee(id)
      if (this.list.length === 1) {
        this.queryParams.page--
      }
      this.getEmployeeList()
      this.$message.success('删除成功')
    },
    async btnRole(id) {
      this.roleList = await getEnableRoleList()
      // 获取员工详细 回显已有角色
      this.currentId = id
      const res = await getEmployeeDetail(this.currentId)
      this.roleIds = res.roleIds
      this.showRoleDialog = true // 先获取数据 再显示弹层
    },
    // 点击确认 掉接口分配角色
    async btnRoleOk() {
      console.log(this.currentId)
      console.log(this.roleIds)

      await assignRoles({ id: this.currentId, roleIds: this.roleIds })
      this.$message.success('分配角色成功')
      this.showRoleDialog = false
    }
  }
}
</script>

<style lang="scss" scoped>
.app-container {
  background: #fff;
  display: flex;
  .left {
    width: 280px;
    padding: 20px;
    border-right: 1px solid #eaeef4;
  }
  .right {
    flex: 1;
    padding: 20px;
    .opeate-tools {
      margin:10px ;
    }
    .username {
      height: 30px;
      width: 30px;
      line-height: 30px;
      text-align: center;
      border-radius: 50%;
      color: #fff;
      background: #04C9BE;
      font-size: 12px;
      display:inline-block;
    }
  }
}

</style>
